package com.taotao.sso.service;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.taotao.common.Service.RedisService;
import com.taotao.sso.mapper.UserMapper;
import com.taotao.sso.pojo.User;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.SystemUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import sun.misc.resources.Messages_pt_BR;

import javax.swing.*;
import java.io.IOException;
import java.util.Date;

/**
 * Created by zjj on 2018/12/14.
 */
@Service
public class UserService {
    private static final ObjectMapper MAPPER = new ObjectMapper();
    @Autowired
    private RedisService redisService;
    @Autowired
    private UserMapper userMapper;

    public Boolean check(String param, Integer type) {
        if(type <1 || type>3){
            return  null;
        }
        User record = new User();
        switch (type){
            case 1:
                record.setUsername(param);
                break;
            case 2:
                record.setPhone(param);
                break;
            case 3:
                record.setEmail(param);
                break;
            default:
                return null;
        }
        return this.userMapper.selectOne(record) == null;
    }

    public Boolean saveUser(User user) {
        user.setId(null);
        user.setCreated(new Date());
        user.setUpdated(user.getCreated());

        user.setPassword(DigestUtils.md5Hex(user.getPassword()));
        return this.userMapper.insert(user)==1;

    }

    public String doLogin(String username, String password) throws Exception {
        User record = new User();
        record.setUsername(username);
       User user = this.userMapper.selectOne(record);

       if(user==null){
           return null;
       }
       if(!StringUtils.equals(DigestUtils.md5Hex(password),user.getPassword())){
           return null;
       }
       //denglu success
        String token = DigestUtils.md5Hex(System.currentTimeMillis()+username);
       //将用户数据保存到redis中
        this.redisService.set("TOKEN_"+ token, MAPPER.writeValueAsString(user),60*30);
        return token;
    }

    public User queryUserByToken(String token) {
        String jsonData = this.redisService.get("TOKEN_"+token);
        if(StringUtils.isEmpty(jsonData)){
            return null;
        }
        try {
            this.redisService.expire("TOKEN_"+token,30*60);
            return MAPPER.readValue(jsonData,User.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
